package org.vsg.stock.core.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

public class StockDateUtilExtensionImpl implements StockDateUtilExtension,InitializingBean {
	
	
	private static List<String> notTradeDays = null;
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");

	private static final Logger logger = LoggerFactory.getLogger(StockDateUtilExtensionImpl.class);	
	
	private String tradedaysProp;

	public String getTradedaysProp() {
		return tradedaysProp;
	}

	public void setTradedaysProp(String tradedaysProp) {
		this.tradedaysProp = tradedaysProp;
	}



	@Override
	public int getDifferenceValue(String stkCode, Date relativeDate, Date targetDate) {
		
		Calendar tmpCale = Calendar.getInstance();
		tmpCale.setTime( relativeDate );
		
		// -- after date ---
		int index = 0;
		if (targetDate.after( relativeDate ) ) {
			
			while (tmpCale.getTime().before( targetDate ) ) {

				if (isTradingDate(tmpCale) ) {
					index++;
				}
				tmpCale.add( Calendar.DATE , 1);				
			}
		}
		else if (targetDate.before( relativeDate ) ) {
			while (tmpCale.getTime().after( targetDate ) ) {

				if (isTradingDate(tmpCale) ) {
					index--;
				}
				tmpCale.add( Calendar.DATE , -1);				
			}			
		}

		return index;
	}

	@Override
	public  boolean isTradingDate(Date date) {
		Date tmpDate = null;
		Calendar tmpCale = Calendar.getInstance();
		tmpCale.setTime(date);		
	
		return isTradingDate(tmpCale);
	}

	@Override	
	public boolean isTradingDate(Calendar tmpCale) {
		
		if (tmpCale.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY 
				|| tmpCale.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ) {
			return false;
		}
		
		String dateStr = sdf.format( tmpCale.getTime() );
		if (notTradeDays.contains( dateStr )) {
			return false;
		}

		return true;
	}	
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		
		InputStream is = null;
		List<String> lines = null;		
		
		// --- init property data ---
		try {
			
			if (tradedaysProp == null) {
				is = ClassLoader.getSystemResourceAsStream("nottradedays.txt");
				logger.info( "property 'stock.tradedays' is null ! " );
			} else {
				is = new FileInputStream( tradedaysProp );
			}
			if (is != null) {
				lines = IOUtils.readLines(is);
			} else {
				lines = new Vector();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					is = null;
				}
			}
		}
		notTradeDays = lines;			
		
	}
	
	
	
}
